import { SecurityManager } from './SecurityManager';

export interface BackupData {
  accounts: any[];
  networks: any[];
  settings: any;
  timestamp: number;
  version: string;
}

export class BackupManager {
  private static readonly BACKUP_KEY = 'qkl_wallet_backup';

  // 创建备份
  static async createBackup(password: string): Promise<string> {
    try {
      // 获取所有钱包数据
      const accounts = await chrome.storage.local.get(['accounts']);
      const networks = await chrome.storage.local.get(['networks']);
      const settings = await chrome.storage.local.get(['settings']);

      const backupData: BackupData = {
        accounts: accounts.accounts || [],
        networks: networks.networks || [],
        settings: settings.settings || {},
        timestamp: Date.now(),
        version: '1.0.0'
      };

      // 加密备份数据
      const encryptedBackup = SecurityManager.encryptData(
        JSON.stringify(backupData),
        password
      );

      return encryptedBackup;
    } catch (error) {
      throw new Error('创建备份失败: ' + error.message);
    }
  }

  // 恢复备份
  static async restoreBackup(encryptedBackup: string, password: string): Promise<void> {
    try {
      // 解密备份数据
      const decryptedData = SecurityManager.decryptData(encryptedBackup, password);
      const backupData: BackupData = JSON.parse(decryptedData);

      // 验证备份数据
      if (!this.validateBackupData(backupData)) {
        throw new Error('无效的备份数据');
      }

      // 恢复数据到存储
      await chrome.storage.local.set({
        accounts: backupData.accounts,
        networks: backupData.networks,
        settings: backupData.settings
      });

    } catch (error) {
      throw new Error('恢复备份失败: ' + error.message);
    }
  }

  // 验证备份数据
  private static validateBackupData(data: any): boolean {
    return (
      data &&
      typeof data === 'object' &&
      Array.isArray(data.accounts) &&
      Array.isArray(data.networks) &&
      typeof data.settings === 'object' &&
      typeof data.timestamp === 'number' &&
      typeof data.version === 'string'
    );
  }

  // 导出私钥（需要密码确认）
  static async exportPrivateKey(address: string, password: string): Promise<string> {
    try {
      const accounts = await chrome.storage.local.get(['accounts']);
      const account = accounts.accounts?.find((acc: any) => acc.address === address);
      
      if (!account) {
        throw new Error('账户不存在');
      }

      // 这里需要用户再次输入密码来解密私钥
      const decryptedPrivateKey = SecurityManager.decryptData(account.privateKey, password);
      
      return decryptedPrivateKey;
    } catch (error) {
      throw new Error('导出私钥失败: ' + error.message);
    }
  }

  // 生成备份文件
  static generateBackupFile(backupData: string): Blob {
    const blob = new Blob([backupData], { type: 'application/json' });
    return blob;
  }

  // 下载备份文件
  static downloadBackup(backupData: string, filename: string = 'qkl-wallet-backup.json'): void {
    const blob = this.generateBackupFile(backupData);
    const url = URL.createObjectURL(blob);
    
    const a = document.createElement('a');
    a.href = url;
    a.download = filename;
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    
    URL.revokeObjectURL(url);
  }

  // 从文件导入备份
  static async importBackupFromFile(file: File, password: string): Promise<void> {
    return new Promise((resolve, reject) => {
      const reader = new FileReader();
      
      reader.onload = async (event) => {
        try {
          const backupData = event.target?.result as string;
          await this.restoreBackup(backupData, password);
          resolve();
        } catch (error) {
          reject(error);
        }
      };
      
      reader.onerror = () => {
        reject(new Error('读取文件失败'));
      };
      
      reader.readAsText(file);
    });
  }

  // 获取备份信息
  static async getBackupInfo(): Promise<{
    hasBackup: boolean;
    lastBackupTime?: number;
    accountCount: number;
  }> {
    try {
      const accounts = await chrome.storage.local.get(['accounts']);
      const backupInfo = await chrome.storage.local.get(['lastBackupTime']);
      
      return {
        hasBackup: accounts.accounts && accounts.accounts.length > 0,
        lastBackupTime: backupInfo.lastBackupTime,
        accountCount: accounts.accounts?.length || 0
      };
    } catch (error) {
      return {
        hasBackup: false,
        accountCount: 0
      };
    }
  }

  // 自动备份（定期执行）
  static async autoBackup(password: string): Promise<void> {
    try {
      const backupData = await this.createBackup(password);
      await chrome.storage.local.set({
        autoBackup: backupData,
        lastBackupTime: Date.now()
      });
    } catch (error) {
      console.error('自动备份失败:', error);
    }
  }

  // 清理旧备份
  static async cleanupOldBackups(): Promise<void> {
    try {
      const result = await chrome.storage.local.get(['lastBackupTime']);
      const lastBackupTime = result.lastBackupTime;
      
      // 如果备份超过30天，提醒用户
      if (lastBackupTime && Date.now() - lastBackupTime > 30 * 24 * 60 * 60 * 1000) {
        // 可以发送通知提醒用户更新备份
        console.log('备份已过期，建议创建新备份');
      }
    } catch (error) {
      console.error('清理备份失败:', error);
    }
  }
}
